#!/usr/bin/python
from sys import argv
import email
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
import os
import logging

body = MIMEMultipart('form-data') 
attachments = []

logger = logging

def multipart_parser(message, data=None, idx=0):
	logger.debug('%s' % (message.get_content_type()))
	pass

def rfc822_parser(message, data=None, idx=0):
	logger.debug('%s' % (message.get_content_type()))

def default_parser(message, data=None, idx=0):
	logger.debug('%s' % message.get_content_type())
        filename = get_file_name(message)
	logger.debug(filename)
        contentType = message.get_content_type()
        payload = message.get_payload(decode=True)

        if not contentType:
            contentType = "application/octet-stream"

        mimeItem = MIMEBase(*contentType.split("/"))
        mimeItem.add_header("Content-Disposition", "form-data",
                                name="file%s" % idx, filename=filename)
        # TODO: Encode the payload?
        mimeItem.set_payload(payload)

        # TODO: Handle this better...?
        for hdr in ['MIME-Version','Content-Transfer-Encoding']:
		del mimeItem[hdr]

	if None != data:
		data.attach(mimeItem)


	
mime_handler = {
			'message/rfc822': rfc822_parser,
			'multipart/mixed': multipart_parser,
			'multipart/alternative': multipart_parser,
			'multipart': multipart_parser,
}

def get_handler(content_type):
	if mime_handler.has_key(str(content_type)):
		handler = mime_handler[str(content_type)]
	else:
		main_type = content_type.split('/')[0]
		if mime_handler.has_key(main_type):
			handler = mime_handler[main_type]
		else:
			handler = default_parser
	return handler
	
def handle_parts(msg, data=None, idx=0):
	msg_str = ''''''
	for part in msg.walk():
		handler = get_handler(part.get_content_type())
		handler(part, data, idx)
	if None != data:
		msg_str = data.as_string()
			
	return msg_str

def handle_part(msg, data=None, idx=0):
	handler = get_handler(msg.get_content_type())
        handler(msg, data, idx)
	

def test_encode(msg):
	for part in msg.walk():
		if part.get_content_maintype() == 'text':
			s = part.get_payload(decode=True)
			paras =  part.get_params([], )
			#for t in paras:
			#	if 'charset' == t[0]:
			#		s = s.decode(t[1])
			print s
				
def get_file_name(msg):
	filename = msg.get_filename()
	if None == filename:
		p = msg.get_params([],)
		for t in p:
			if 'name' == t[0]:
				filename = t[1]
				break
	return filename

if __name__ == '__main__':
	
	f = open(argv[1])
	msg = email.message_from_file(f)
	#mail_str = handle_parts(msg, body, 0)
	test_encode(msg)	
	f.close()

